package indi.cloud.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;

/**
 * @author yangyifan
 * @version 1.0
 * @date 2021/3/23 11:20
 * @Description
 */
public class DataUtils {
    private static final Logger logger = LoggerFactory.getLogger(DataUtils.class);

    /**
     * 乘100，并保留两位小数
     *
     * @param value
     */
    public static BigDecimal perCentConvert(Object value) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return null;
        }
        try {
            return strToDeci(value, 6).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_DOWN);
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 根据逗号分隔，并返回数组
     *
     * @param str
     * @return
     */
    public static void strToArrByObject(JSONObject obj, String... key) {
        if (obj != null) {
            Stream.of(key).forEach(x -> {
                if (obj.containsKey(x) && obj.get(x) != null && obj.get(x) instanceof List == false) {
                    obj.put(x, strSplit(obj.getString(x)));
                }
            });
        }
    }


    /**
     * 根据逗号分隔，并返回数组
     *
     * @param str
     * @return
     */
    public static void strSplitByObject(JSONObject obj) {
        if (obj != null) {
            obj.keySet().stream().forEach(x -> {
                String value = ObjectUtils.toString(obj.getString(x), "");
                if (value.contains(",")) {
                    obj.put(x, strSplit(value));
                }
            });
        }
    }


    /**
     * 根据逗号分隔，并返回数组
     *
     * @param str
     * @return
     */
    public static List<String> strSplit(String str) {
        if (StringUtils.isBlank(str)) {
            return new ArrayList<>();
        }
        return Arrays.asList(str.split(","));
    }

    public static JSONObject arrToMap(JSONArray ansData) {
        JSONObject data = new JSONObject();
        for (int i = 0; i < ansData.size(); i++) {
            JSONObject singleEle = ansData.getJSONObject(i);
            String name = singleEle.getString("name");
            data.put(name, singleEle);
        }
        return data;
    }

    /**
     * String 转BigDecimal
     *
     * @return
     */
    public static BigDecimal strToDeci(Object value, int i) {
        BigDecimal ret = null;
        try {
            if (value == null) {
                return null;
            }
            if (value != null) {

                if (value instanceof BigDecimal) {
                    ret = (BigDecimal) value;
                } else if (value instanceof String) {
                    value = ((String) value).trim();
                    if (value.equals("-")) {
                        return null;
                    }
                    if (((String) value).indexOf("E") > 0) {
                        BigDecimal bd = new BigDecimal(String.valueOf(value));
                        value = bd.toPlainString();
                    }
                    if (StringUtils.isBlank(String.valueOf(value))) {
                        return null;
                    }
                    ret = new BigDecimal((String) value);
                } else if (value instanceof BigInteger) {
                    ret = new BigDecimal((BigInteger) value);
                } else if (value instanceof Number) {
                    if (String.valueOf(value).indexOf("E") > 0) {
                        BigDecimal bd = new BigDecimal(String.valueOf(value));
                        value = bd.toPlainString();
                        ret = new BigDecimal((String) value);
                    } else {
                        if (value instanceof Double) {
                            if (Double.isNaN(Double.valueOf(String.valueOf(value))) || Double.isInfinite(Double.valueOf(String.valueOf(value)))) {
                                ret = new BigDecimal(0);
                            } else {
                                ret = new BigDecimal(((Number) value).doubleValue());
                            }
                        }
                        if (value instanceof Integer) {
                            ret = new BigDecimal(value.toString());
                        }
                        if (value instanceof Float) {
                            ret = new BigDecimal(value.toString());
                        }
                        if (value instanceof Long) {
                            ret = new BigDecimal(value.toString());
                        }
                    }
                } else {
                    throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
                }
            } else {
                throw new ClassCastException("获取科目数值为 [" + value + "]");
            }
        } catch (Exception e) {
            throw new ClassCastException("数字转BigDeciaml失败 [" + value + "]");
        }
        ret = ret.setScale(i, BigDecimal.ROUND_HALF_DOWN);
        return ret;
    }

    public static String strToNumber(Object value) {
        try {
            if ("MAX".equalsIgnoreCase(String.valueOf(value))) {
                return "MAX";
            }
            if ("MIN".equalsIgnoreCase(String.valueOf(value))) {
                return "MIN";
            }
            BigDecimal bigDecimal = strToDeci(value, 4);
            return bigDecimal == null ? null : bigDecimal.toPlainString();
        } catch (Exception e) {
            return null;
        }
    }


    /**
     * 任意值缺失判定
     * 任意值存在空，返回true
     *
     * @param value
     * @return
     */
    public static boolean arbitrarilyNull(BigDecimal... value) {
        return Arrays.stream(value).anyMatch(x -> isNull(x));
    }


    public static boolean isNull(BigDecimal val) {
        return val == null ? true : false;
    }


    /**
     * 判断字符串中是否包含中文
     *
     * @param str 待校验字符串
     * @return 是否为中文
     * @warn 不能校验是否为中文标点符号
     */
    private static Pattern p = Pattern.compile("[\u4e00-\u9fa5]");

    public static boolean isContainChinese(String str) {

        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }


    /**
     * 传入的参数roundingMode小于0或大于7就会报错
     */
    public static final int DIVIDE_SALE = 7;
    /**
     * 4:RoundingMode.HALF_UP:四舍五入
     */
    public static final int ROUND = 4;

    public static String fmtMicrometer(String text) {

        if (text == null) {
            return null;
        }
        DecimalFormat df = null;

        if (text.indexOf(".") > 0) {

            if (text.length() - text.indexOf(".") - 1 == 0) {

                df = new DecimalFormat("###,##0.");

            } else if (text.length() - text.indexOf(".") - 1 == 1) {

                df = new DecimalFormat("###,##0.0");

            } else if (text.length() - text.indexOf(".") - 1 == 2) {

                df = new DecimalFormat("###,##0.00");

            } else if (text.length() - text.indexOf(".") - 1 == 3) {

                df = new DecimalFormat("###,##0.000");

            } else if (text.length() - text.indexOf(".") - 1 == 4) {

                df = new DecimalFormat("###,##0.0000");

            } else if (text.length() - text.indexOf(".") - 1 == 5) {

                df = new DecimalFormat("###,##0.00000");

            } else {
                return text;
            }

        } else {

            df = new DecimalFormat("###,##0");

        }

        double number = 0.0;

        try {

            number = Double.parseDouble(text);

        } catch (Exception e) {

            number = 0.0;

        }
        if (df == null) {
            System.out.println(number);
        }
        return df.format(number);

    }

    public static String unitChange(String unit) {
        unit = unit.replace("(万)", "(元)").replace("（万）", "(元)").replace("(万元)", "(元)").replace("（万元）", "(元)");
        return unit;
    }

}
